package com.baizhi.action;

import com.baizhi.service.AdminService;
import com.baizhi.service.impl.AdminServiceImpl;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class AdminAction {
    private String username;
    private String password;
    private String validateCode;
    private String errorMsg;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getValidateCode() {
        return validateCode;
    }

    public void setValidateCode(String validateCode) {
        this.validateCode = validateCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public String login() throws UnsupportedEncodingException {
        AdminService adminService=new AdminServiceImpl();
        HttpServletRequest req = ServletActionContext.getRequest();
        HttpSession session=req.getSession();
        String realCode = (String) session.getAttribute("realCode");
        if (realCode==null){
            errorMsg= URLEncoder.encode( "验证码已失效","utf-8");
            return "loginError";
        }
        if (validateCode==null||validateCode.isEmpty()||!validateCode.equalsIgnoreCase(realCode)){
            errorMsg=URLEncoder.encode( "验证码错误","utf-8");
            return "loginError";
        }
        if (username==null||username.isEmpty()||password==null||password.isEmpty()){
            errorMsg=URLEncoder.encode( "用户名和密码为必填项","utf-8");
            return "loginError";
        }
        Boolean flag = adminService.login(username, password);
        if (!flag){
            errorMsg=URLEncoder.encode( "用户名或密码错误","utf-8");
            return "loginError";
        }else {
            session.setAttribute("username",username);
            session.removeAttribute("realCode");
            return "loginSuccess";
        }
    }

    public String logout(){
        HttpServletRequest req = ServletActionContext.getRequest();
        HttpSession session=req.getSession();
        //session.invalidate();
        session.removeAttribute("username");
        return "logoutSuccess";
    }
}
